//
//  HomeManager.swift
//  home
//
//  Created by Yun Zeng on 2018/11/25.
//  Copyright © 2018 Yun Zeng. All rights reserved.
//


import Foundation

//
// 同一个家庭可以多个用户之间相互分享
// 因此一个用户可以有多个家庭
// HomeManager 负责用户的家庭的管理与更新
//

protocol HomeUpdateObserver {
    func homeDataUpdate()
}

class HomeManager {
    // 用户当前的家庭
    var current: Home?
    
    static let instance = { () -> HomeManager in
        let manager = HomeManager()
        let client = CloudClient.instance
        _ = client.addObserver(path: "home", controller: manager)
        return manager
    }()
    
    // MARK: 设置当前用户操作的家庭
    func setCurrentHome(id: String) {
        if let home = self.current, home.id == id {
            home.sync()
            return
        }
        self.current = Home.new(id: id)
        self.current?.sync()
    }
    
    // 观察家庭数据变化
    var observers = [String: HomeUpdateObserver]()
    func addObserver(identify: String, observer: HomeUpdateObserver)  {
        self.observers[identify] = observer
    }
    func removeObserver(identify: String) {
        self.observers.removeValue(forKey: identify)
    }
}

extension HomeManager {
    func handleMessage(msg: CloudMessage) -> CloudMessageError {
        guard let data = msg.data else {
            return .invalidParameter
        }
        
        if msg.method == .get || msg.method  == .put {
            // 从服务器获取的家庭数据新建家庭
            Logger.Info("mark: \(msg.description)")
            if let home = Home(data: data) {
                _ = home.save()
                if self.current?.id == home.id {
                    self.current = home
                    for observer in self.observers {
                        observer.value.homeDataUpdate()
                    }
                }
            }
        }
        return .success
    }
}

extension HomeManager: CloudMessageHandler {
    func handle(msg: CloudMessage) -> CloudMessageError {
        if msg.path == HomeMessagePath.home.rawValue {
            return self.handleMessage(msg: msg)
        }
        
        if let home = self.current {
            if home.id == msg.home {
                return home.handle(msg: msg)
            }
        }
        return .success
    }
    
    func clientStateChange(state: CloudClient.State) {
        self.current?.clientStateChange(state: state)
    }
}











